package com.financal.controller;
import com.financal.client.CoreUserIfoClient;
import com.financal.exception.Assert;
import com.financal.result.R;
import com.financal.result.ResponseEnum;
import com.financal.util.NoteUtils;
import io.swagger.annotations.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Api(value = "LendItemController")
@RestController
@RequestMapping("/api/sms")
@CrossOrigin
public class ApiSmsController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CoreUserIfoClient coreUserIfoClient;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号", required = true) @PathVariable String mobile){
        if(mobile!=null){
            //判断手机号是否已经注册
            boolean b = coreUserIfoClient.checkMobile(mobile);
            Assert.isTrue(b == false, ResponseEnum.MOBILE_EXIST_ERROR);
            //生成六位随机验证码
            Integer i = (int)((Math.random()*9+1)*100000);
            String code = String.valueOf(i);
            NoteUtils noteUtils = new NoteUtils();

            //将验证码存入redis
            redisTemplate.opsForValue().set("code:" + mobile, code, 5, TimeUnit.MINUTES);

            //发送短信
            String message = noteUtils.ToNote(mobile, code);

            System.out.println(code+"massage"+message);
            return R.ok().data("0",message);
        }
        return R.error().data("1","发送失败!");
    }


}
